<template>
  <view class="container">
    <!-- 搜索栏 -->
    <view 
      class="search-bar"
      :class="{ focused: isSearchFocused }"
    >
      <view class="search-box">
        <image src="/static/home/search.png" class="search-icon" />
        <input
          v-model="searchKeyword"
          placeholder="搜索商品"
          class="search-input"
          confirm-type="search"
          @confirm="handleSearch"
          @focus="isSearchFocused = true"
          @blur="isSearchFocused = false"
        />
        <text 
          v-if="searchKeyword" 
          class="clear-btn"
          @tap.stop="clearSearch"
        >×</text>
      </view>
      <text 
        class="search-btn"
        :class="{ active: searchKeyword }"
        @tap="handleSearch"
      >搜索</text>
    </view>

    <view class="content">
      <!-- 左侧分类导航 -->
      <scroll-view class="category-nav" scroll-y>
        <view 
          v-for="category in categories" 
          :key="category.id"
          class="nav-item"
          :class="{ active: currentCategory?.id === category.id }"
          @tap="switchCategory(category)"
        >
          <text class="nav-text">{{ category.name }}</text>
        </view>
      </scroll-view>

      <!-- 右侧商品列表 -->
      <scroll-view 
        class="product-list" 
        scroll-y
        refresher-enabled
        :refresher-triggered="refreshing"
        @refresherrefresh="onRefresh"
        @scrolltolower="loadMore"
      >
        <!-- 排序选项 -->
        <view class="sort-header">
          <view class="sort-options">
            <text 
              class="sort-item" 
              :class="{ active: sortField === 'createTime' }"
              @tap="changeSort('createTime')"
            >最新</text>
            <text 
              class="sort-item" 
              :class="{ active: sortField === 'sales' }"
              @tap="changeSort('sales')"
            >销量</text>
          </view>
        </view>

        <!-- 商品网格 -->
        <view class="product-grid">
          <view 
            v-for="product in products" 
            :key="product.id" 
            class="product-card"
            @tap="goToDetail(product.id)"
          >
            <image :src="product.image || '/static/https://fsp-1326500412.cos.ap-chengdu.myqcloud.com/default.png'" mode="aspectFill" class="product-image" />
            <view class="product-info">
              <view class="info-top">
                <text class="product-name">{{ product.name }}</text>
                <text class="product-desc">{{ product.description || '' }}</text>
              </view>
              <view class="product-meta">
                <text class="product-price">¥{{ product.minPrice }}</text>
                <view class="sales-badge">
                  <image src="/static/hot.png" mode="aspectFit" class="hot-icon" />
                  <text class="sales-text">已售{{ product.sales || 0 }}</text>
                </view>
              </view>
            </view>
          </view>
        </view>

        <!-- 加载状态 -->
        <view v-if="loading" class="loading">
          <text class="loading-text">加载中...</text>
        </view>
        <view v-if="!hasMore && products.length > 0" class="no-more">
          <text class="no-more-text">没有更多了</text>
        </view>
        <view v-if="!loading && products.length === 0" class="empty">
          <text class="empty-text">暂无商品</text>
        </view>
      </scroll-view>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue';
import { onShow } from '@dcloudio/uni-app';
import { listCategoryVoByPageUsingPost } from '../../backend/categoryController';
import { listProductVoByPageUsingPost } from '../../backend/productController';
import type { API } from '../../backend/typings';

// 状态管理
const loading = ref(false);
const refreshing = ref(false);
const hasMore = ref(true);
const currentCategory = ref<API.CategoryVO>();
const products = ref<API.ProductVO[]>([]);
const categories = ref<API.CategoryVO[]>([
  { id: 0, name: '全部', createTime: '', updateTime: '' }
]);
const sortField = ref('createTime');
const sortOrder = ref('desc');
const searchKeyword = ref('');
const isSearchFocused = ref(false);

// 查询参数
const queryParams = reactive({
  current: 1,
  pageSize: 10,
  categoryId: undefined as number | undefined,
  sortField: 'createTime',
  sortOrder: 'desc',
  status: 'active'
});

// 获取分类列表
const fetchCategories = async () => {
  try {
    const res = await listCategoryVoByPageUsingPost({
      current: 1,
      pageSize: 10,
    });
    if (res?.code === 0 && res?.data?.records) {
      categories.value = [
        { id: 0, name: '全部', createTime: '', updateTime: '' },
        ...res.data.records
      ];
      if (!currentCategory.value) {
        switchCategory(categories.value[0]);
      }
    }
  } catch (error) {
    console.error('获取分类失败：', error);
    uni.showToast({
      title: '获取分类失败',
      icon: 'none'
    });
  }
};

// 获取商品列表
const fetchProducts = async (refresh = false) => {
  if (loading.value) return;
  loading.value = true;

  try {
    if (refresh) {
      queryParams.current = 1;
    }

    const params = {
      ...queryParams,
      status: 'active',
      name: searchKeyword.value
    };

    // 只有当不是"全部"分类时，才添加categoryId参数
    if (currentCategory.value?.id !== 0) {
      params.categoryId = currentCategory.value?.id;
    }

    const res = await listProductVoByPageUsingPost(params);
    
    if (res?.code === 0 && res?.data?.records) {
      if (refresh) {
        products.value = res.data.records;
      } else {
        products.value = [...products.value, ...res.data.records];
      }
      hasMore.value = res.data.records.length === queryParams.pageSize;
      if (hasMore.value) {
        queryParams.current++;
      }
    }
  } catch (error) {
    console.error('获取商品列表失败：', error);
    uni.showToast({
      title: '获取商品列表失败',
      icon: 'none'
    });
  } finally {
    loading.value = false;
    refreshing.value = false;
  }
};

// 清空搜索
const clearSearch= () => {
  searchKeyword.value = '';
  fetchProducts(true);
};

// 切换分类
const switchCategory = (category: API.CategoryVO) => {
  currentCategory.value = category;
  queryParams.current = 1;
  fetchProducts(true);
};

// 切换排序
const changeSort = (field: string) => {
  if (loading.value) return;
  if (sortField.value === field) {
    sortOrder.value = sortOrder.value === 'desc' ? 'asc' : 'desc';
  } else {
    sortField.value = field;
    sortOrder.value = 'desc';
  }
  queryParams.sortField = field;
  queryParams.sortOrder = sortOrder.value;
  fetchProducts(true);
};

// 下拉刷新
const onRefresh = async () => {
  refreshing.value = true;
  await fetchProducts(true);
};

// 加载更多
const loadMore = () => {
  if (hasMore.value && !loading.value) {
    fetchProducts();
  }
};

// 跳转详情页
const goToDetail = (id?: number) => {
  if (!id) return;
  uni.navigateTo({
    url: `/pages/product/detail?id=${id}`
  });
};

// 新增搜索处理方法
const handleSearch = () => {
  const keyword = searchKeyword.value.trim();
  if (!keyword) {
    uni.showToast({ title: '请输入搜索内容', icon: 'none' });
    return;
  }
  
  searchKeyword.value = '';
  uni.navigateTo({
    url: `/pages/search/search?keyword=${encodeURIComponent(keyword)}`
  });
};

// 初始化数据
const initData = () => {
  fetchCategories();
};

// 页面加载时初始化
onMounted(() => {
  initData();
});

// 每次显示页面时刷新数据
onShow(() => {
  initData();
});
</script>

<style scoped>
.container {
  display: flex;
  flex-direction: column;
  height: 100vh;
  background-color: #f8f8f8;
}

.header {
  padding: 20rpx 30rpx;
  background: #fff;
  text-align: center;
}

.page-title {
  font-size: 36rpx;
  font-weight: 500;
  color: #333;
}

.search-bar {
  display: flex;
  align-items: center;
  gap: 20rpx;
  padding: 20rpx 30rpx;
  background: #fff;
}

.search-bar.focused {
  transform: scale(1.05);
  box-shadow: 0 4rpx 20rpx rgba(0,0,0,0.1);
}

.search-box {
  flex: 1;
  display: flex;
  align-items: center;
  height: 72rpx;
  background: #f5f5f5;
  border-radius: 36rpx;
  padding: 0 30rpx;
}

.search-icon {
  width: 32rpx;
  height: 32rpx;
  margin-right: 16rpx;
}

.search-placeholder {
  color: #999;
  font-size: 28rpx;
}

.content {
  flex: 1;
  display: flex;
  overflow: hidden;
}

.category-nav {
  width: 160rpx;
  height: 100%;
  background-color: #f8f8f8;
}

.nav-item {
  height: 88rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  position: relative;
}

.nav-item.active {
  background-color: #fff;
}

.nav-text {
  font-size: 28rpx;
  color: #666;
  text-align: center;
}

.nav-item.active .nav-text {
  color: #ff5722;
}

.product-list {
  flex: 1;
  height: 100%;
  background: #fff;
}

.product-grid {
  padding: 20rpx;
}

.product-card {
  display: flex;
  padding: 24rpx 0;
  border-bottom: 1rpx solid #f5f5f5;
}

.product-image {
  width: 180rpx;
  height: 180rpx;
  border-radius: 12rpx;
  margin-right: 24rpx;
  background: #f5f5f5;
}

.product-info {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}

.info-top {
  flex: 1;
}

.product-name {
  font-size: 28rpx;
  color: #333;
  font-weight: 500;
  margin-bottom: 12rpx;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
  line-height: 1.4;
}

.product-desc {
  font-size: 24rpx;
  color: #999;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
  line-height: 1.4;
}

.product-meta {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.product-price {
  font-size: 32rpx;
  font-weight: bold;
  color: #ff5722;
}

.sales-badge {
  display: flex;
  align-items: center;
  gap: 4rpx;
  background: #fff2ed;
  padding: 4rpx 12rpx;
  border-radius: 20rpx;
}

.hot-icon {
  width: 24rpx;
  height: 24rpx;
}

.sales-text {
  font-size: 24rpx;
  color: #ff5722;
}

.loading, .no-more, .empty {
  text-align: center;
  padding: 30rpx;
  color: #999;
  font-size: 24rpx;
}

.sort-header {
  padding: 20rpx 30rpx;
  background: #fff;
  border-bottom: 2rpx solid #f5f5f5;
}

.sort-options {
  display: flex;
  gap: 40rpx;
}

.sort-item {
  font-size: 28rpx;
  color: #666;
  position: relative;
  padding: 8rpx 0;
}

.sort-item.active {
  color: #ff5722;
  font-weight: 500;
}

.sort-item.active::after {
  content: '';
  position: absolute;
  bottom: 0;
  left: 50%;
  transform: translateX(-50%);
  width: 40rpx;
  height: 4rpx;
  background: #ff5722;
  border-radius: 2rpx;
}

.search-box:active {
  transform: scale(1.02);
}

.search-btn {
  min-width: 120rpx;
  text-align: center;
  font-size: 28rpx;
  color: #999;
  padding: 12rpx 24rpx;
  border-radius: 36rpx;
  transition: all 0.3s ease;
}

.search-btn.active {
  background: #ff5722;
  color: #fff;
  box-shadow: 0 4rpx 12rpx rgba(255,87,34,0.3);
}
</style> 